import React, { Component } from 'react'
import './GoodsList.scss'
import { countTotalNum } from '../../store/actionCreator'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'

class GoodsList extends Component {
  state = {
    CartList: [],
    allChecked: true,
    checkedNum: 0,
    edit: false,
    totalPrice: 0,
    reducedPrice: 0,
  }
  componentDidMount() {
    let CartList = JSON.parse(window.localStorage.getItem('CartList')) || []
    this.setState({
      CartList,
    })
    this.isAllChecked(CartList)
    this.countTotalPrice(CartList)
  }
  /* 判断是否全选 */
  isAllChecked(arr) {
    var checkedNum = 0
    var allChecked = true
    arr.forEach((v) => {
      if (v.checked) {
        checkedNum += v.num
      } else {
        allChecked = false
      }
    })
    this.setState({
      checkedNum,
      allChecked,
    })
  }
  /* 更改商品数目 */
  changeNum(id, newNum) {
    let CartList = this.state.CartList.map((v) => {
      let item = { ...v }
      if (v.id === id) {
        item.num = newNum
      }
      return item
    })
    this.setCartList(CartList)
    this.isAllChecked(CartList)
    this.props.countTotal(CartList)
    this.countTotalPrice(CartList)
  }
  /* 更改单个商品选中状态 */
  changeChecked(id) {
    let CartList = this.state.CartList.map((v) => {
      let item = { ...v }
      if (v.id === id) {
        item.checked = !item.checked
      }
      return item
    })
    this.isAllChecked(CartList)
    this.setCartList(CartList)
    this.countTotalPrice(CartList)
  }
  /* 全选按钮 */
  selectAll() {
    let allChecked = !this.state.allChecked
    let CartList = this.state.CartList.map((v) => {
      let item = { ...v }
      item.checked = allChecked
      return item
    })
    this.setCartList(CartList)
    this.isAllChecked(CartList)
    this.countTotalPrice(CartList)
  }
  /* 删除选择商品 */
  deleteSelect() {
    let CartList = this.state.CartList.filter((v) => {
      let item = { ...v }
      return !item.checked
    })
    this.isAllChecked(CartList)
    this.setCartList(CartList)
    this.props.countTotal(CartList)
    this.countTotalPrice(CartList)
  }
  /* 计算选中商品的总价 */
  countTotalPrice(arr) {
    let totalPrice = 0
    let reducedPrice = 0
    arr.forEach((v) => {
      if (v.checked) {
        totalPrice += v.price * v.num
        reducedPrice += (v.oldPrice - v.price) * v.num 
      }
    })
    totalPrice=Math.floor(totalPrice*100)/100
    reducedPrice=Math.floor(reducedPrice*100)/100
    this.setState({
      totalPrice,
      reducedPrice,
    })
  }
  /* 更改state/store/localStorage中的CartList数据 */
  setCartList(CartList) {
    this.setState({
      CartList,
    })
    this.props.changeProductReducer(['CartList'], CartList)
  }

  render() {
    const { CartList } = this.state
    return (
      <div className="cartCon">
        {/* ------------------- */}
        <div
          className="cartCon"
          style={this.props.totalNum ? {} : { display: 'none' }}
        >
          <div className="cartConTop">
            <div className="cartConTopLt">购物车</div>
            <div
              className="cartConTopRt"
              onClick={() => {
                this.setState({
                  edit: !this.state.edit,
                })
              }}
            >
              {this.state.edit ? '完成' : '编辑'}
            </div>
          </div>
          {/* 购物车列表 */}
          {CartList.map((v) => (
            <div className="cartGoodsItem" key={v.id}>
              <i
                className="checkedBtn"
                style={{
                  backgroundPosition: v.checked ? '0 -1.13rem' : '0 -0.90rem',
                }}
                onClick={() => {
                  this.changeChecked(v.id)
                }}
              ></i>
              <div className="infoBox">
                <div className="infoBoxTop">
                  <span className="infoBoxTop1">限时抢购中</span>
                  <span className="infoBoxTop2">距优惠结束</span>
                  <span className="infoBoxTop3">3天14小时</span>
                </div>
                <div className="infoBoxBot">
                  <img
                    src={v.pic}
                    alt=""
                    className="infoBoxBotPic"
                    onClick={() => {
                      this.props.history.push('/ProductDetail/?id=' + v.itemId)
                    }}
                  />
                  <div className="infoBoxBotRt">
                    <div className="infoBoxBotTit">
                      <span className="infoBoxBot1">{v.itemTag}</span>
                      <span className="infoBoxBot2">{v.name}</span>
                    </div>
                    <div className="infoBoxBotSpec">
                      {v.SkuSpecList.map((val) => (
                        <span key={val.id}>{val.value}</span>
                      ))}

                      <i
                        className="iconfont icon-jiantouzuo
"
                      ></i>
                    </div>
                    <div className="infoBoxBotPrice">
                      <div className="infoBoxBotLt">
                        <span className="infoBoxBotNowPrice">¥{v.price}</span>
                        <span className="infoBoxBotOldPrice">
                          ¥{v.oldPrice}
                        </span>
                      </div>
                      <div className="infoBoxBotRt">
                        <span
                          className="infoBoxBotRtSub"
                          onClick={() => {
                            if (v.num <= 1) return
                            this.changeNum(v.id, v.num - 1)
                          }}
                        >
                          -
                        </span>
                        <input
                          type="text"
                          className="infoBoxBotNum"
                          value={v.num}
                          onChange={(e) => {
                            this.changeNum(
                              v.id,
                              Number(e.target.value.replace(/[^0-9]/g, ''))
                            )
                          }}
                        />
                        <span
                          className="infoBoxBotRtAdd"
                          onClick={() => {
                            this.changeNum(v.id, v.num + 1)
                          }}
                        >
                          +
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
          {/* 底部下单按钮开始 */}
          <div
            className="cartGoodListBot"
            style={{ display: this.state.edit ? 'none' : '' }}
          >
            <div className="left">
              <div className="botLt">
                <i
                  className="checkedBtn"
                  style={{
                    backgroundPosition: this.state.allChecked
                      ? '0 -1.13rem'
                      : '0 -0.90rem',
                  }}
                  onClick={() => {
                    this.selectAll()
                  }}
                ></i>
                已选({this.state.checkedNum})
              </div>
              <div className="botRt">
                <div className="total">合计: ¥{this.state.totalPrice}</div>
                <div className="promotionPrice">
                  已经优惠:¥{this.state.reducedPrice}
                </div>
              </div>
            </div>
            <div
              className="rt"
              style={this.state.checkedNum ? {} : { backgroundColor: '#ccc' }}
            >
              下单
            </div>
          </div>
          {/* 底部下单按钮结束 */}
          {/* 底部编辑按钮开始 */}
          <div
            className="cartGoodListBot"
            style={{ display: !this.state.edit ? 'none' : '' }}
          >
            <div className="left">
              <div className="botLt">
                <i
                  className="checkedBtn"
                  style={{
                    backgroundPosition: this.state.allChecked
                      ? '0 -1.13rem'
                      : '0 -0.90rem',
                  }}
                  onClick={() => {
                    this.selectAll()
                  }}
                ></i>
                已选({this.state.checkedNum})
              </div>
            </div>
            <div
              className="rt"
              style={this.state.checkedNum ? {} : { backgroundColor: '#ccc' }}
              onClick={() => {
                this.deleteSelect()
              }}
            >
              删除所选
            </div>
          </div>
          {/* 底部编辑按钮结束 */}
        </div>
        {/* -------------------- */}
        {/* 购物车为空渲染这里 开始*/}
        <div
          className="emptyCart"
          style={!this.props.totalNum ? {} : { display: 'none' }}
        >
          <div className="bg"></div>
          <div className="txt">去添加点什么吧</div>
        </div>
        {/* 购物车为空渲染这里 结束*/}
      </div>
    )
  }
}
const mapStateToProps = (state) => {
  return {
    productInfo: state.getIn(['productReducer', 'productInfo']),
    CartList: state.getIn(['productReducer', 'CartList']),
    totalNum: state.getIn(['productReducer', 'totalNum']),
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    changeProductReducer: (arr, val) => {
      let action = (arr, val) => {
        return {
          type: 'UPDATE_PRODUCT_DETAIL',
          payload: {
            keyArr: arr,
            val: val,
          },
        }
      }
      dispatch(action(arr, val))
    },
    /* 计算购物总数开始 */
    countTotal: (arr) => {
      var num = 0
      arr.forEach((v) => {
        num += v.num
      })
      dispatch(countTotalNum(num))
    },

    /* 计算购物总数结束 */
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(GoodsList))
